package com.example.lcl.exp2019_2;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends ListActivity {
    //数据库适配对象,用于操作数据库
    private DBAdapter db=null;
    private List<People> peopleList = new ArrayList<>();
    private People people = new People();
    private ItemAdapter itemAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Context context = this;

        itemAdapter = new ItemAdapter(this);

        //创建数据库适配对象
        db=new DBAdapter(this);


        //创建数据库
        if (!db.createDB()){
            Toast.makeText(MainActivity.this, "创建数据库失败!", Toast.LENGTH_SHORT).show();
            return;
        }

        //第一次查询
        peopleList = db.QueryAll();
        setListAdapter(itemAdapter);

        Button button_add = (Button)findViewById(R.id.add);
        Button button_modify = (Button)findViewById(R.id.modify);
        Button button_delete = (Button)findViewById(R.id.delete);
        Button button_query = (Button)findViewById(R.id.query);

        //插入
        button_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                people = GetInput();
                if (db.insert(people)) {
                    peopleList = null;
                    peopleList = db.QueryAll();
                    setListAdapter(itemAdapter);
                    System.out.println("插入成功");
                }
                else
                    System.out.print("插入出错");
            }
        });

        //修改
        button_modify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                people = GetInput();
                if (db.update(people)) {
                    peopleList = null;
                    peopleList = db.QueryAll();
                    setListAdapter(itemAdapter);
                    System.out.println("修改成功");
                }
                else
                    System.out.println("修改失败");
            }
        });

        //删除
        button_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (db.delete(people.getId())){
                    peopleList = null;
                    peopleList = db.QueryAll();
                    setListAdapter(itemAdapter);
                    System.out.println("删除成功");
                }
                else
                    System.out.println("删除失败");
            }
        });

        //查询
        button_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final EditText text = (EditText)findViewById(R.id.ageText);
                int age = Integer.parseInt(text.getText().toString());
                peopleList = null;
                peopleList = db.QueryByAge(age);

                String msg = new String();
                for (int i = 0;i < peopleList.size();i++){
                    msg += "ID:" + peopleList.get(i).getId();
                    msg += "Name" + peopleList.get(i).getName();
                    msg += "Age:" + peopleList.get(i).getAge();
                    msg += "Height" + peopleList.get(i).getHeight();
                    if (i != peopleList.size() - 1) msg += "\n";
                }
                Toast.makeText(context,msg,Toast.LENGTH_LONG).show();
                setListAdapter(itemAdapter);
            }
        });



    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        db.close();
    }

    public People GetInput() {
        final EditText textView_name = (EditText)findViewById(R.id.nameText);
        final EditText textView_age = (EditText)findViewById(R.id.ageText);
        final EditText textView_height = (EditText)findViewById(R.id.heightText);

        final String name = textView_name.getText().toString();
        final int age = Integer.parseInt(textView_age.getText().toString());
        final float height = Float.parseFloat(textView_height.getText().toString());

        people.setName(name);
        people.setAge(age);
        people.setHeight(height);

        return people;
    }


    public final class ItemAdapter extends BaseAdapter {

        //实例化布局对象————用于实例化每行的布局->View对象
        private LayoutInflater mInflater;

        public ItemAdapter(Context context) {
            this.mInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return peopleList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }


        /*
         * 获取指定一行的对应的View对象————不存在则创建之
         * position——当前要显示的数据的位置（行号）
         * convertView——可利用的以前的View对象（上下滚动时，利用旧的View对象显示新的内容）
         *               如果此行为空，则需要动态创建新的View对象
         * parent——父控件（上层的ListView）
         * */
        @Override
        public View getView(int positon, View convertView, ViewGroup parent) {
            //实例化一行的布局
            View rowview = mInflater.inflate(R.layout.item, null);
            //找到行内的子控件
            TextView textView_id = (TextView) rowview.findViewById(R.id.id);
            TextView textView_name = (TextView) rowview.findViewById(R.id.name);
            TextView textView_age = (TextView) rowview.findViewById(R.id.age);
            TextView textView_height = (TextView) rowview.findViewById(R.id.height);
            //设置宽度
            DisplayMetrics dm = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            int w = dm.widthPixels / 16; // 当前分辨率 宽度 分为16份

            textView_id.setWidth(w * 4);
            textView_name.setWidth(w * 4);
            textView_age.setWidth(w * 4);
            textView_height.setWidth(w * 4);
            //子控件赋值
            textView_id.setText(String.valueOf(peopleList.get(positon).getId()));
            textView_name.setText(String.valueOf(peopleList.get(positon).getName()));
            textView_age.setText(String.valueOf(peopleList.get(positon).getAge()));
            textView_height.setText(String.valueOf(peopleList.get(positon).getHeight()));

            //行点击监听
            rowview.setOnClickListener(new viewClickListener(positon));


            return rowview;
        }
    }

    //重写此方法——点击一行时的回调函数——参数含义同前
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
    }

    //使用内部类实现ListView中每行中按钮的点击监听
    //该监听器会为ListView的每一行提供一个监听器对象，用于监听该行的按钮的点击事件
    class viewClickListener implements View.OnClickListener {
        //记录按钮所在的号
        int position;
        final EditText textView_name = (EditText)findViewById(R.id.nameText);
        final EditText textView_age = (EditText)findViewById(R.id.ageText);
        final EditText textView_height = (EditText)findViewById(R.id.heightText);

        //必须使用自定义的构造函数——因为需要在此通过参数记录该监听器对象监听的行号
        public viewClickListener(int pos) {
            position = pos;
        }

        @Override
        public void onClick(View v){
            people = peopleList.get(position);
            textView_name.setText(String.valueOf(people.getName()));
            textView_age.setText(String.valueOf(people.getAge()));
            textView_height.setText(String.valueOf(people.getHeight()));
        }
    }
}
